package com.example.security1.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.security1.util.Result;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JwtValidateFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 差看是否有token
        String token = request.getHeader("token");
        // 获取请求的路径是什么
        String requestURI = request.getRequestURI();
        //
        if (StringUtils.isNotBlank(token)){
          // 校验token
            boolean verify = JWTUtil.verify(token, "yyl".getBytes());
            if (verify){
                // 解析token
                JWT jwt = JWTUtil.parseToken(token);
                // 荷载的信息   username
                String username = jwt.getPayload().getClaim("username").toString();
                // 资源的信息
                List<String> authorities = (List<String>) jwt.getPayload().getClaim("authorities");
                List<SimpleGrantedAuthority> collect = authorities.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList());
                //
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,null,collect);
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                filterChain.doFilter(request,response);
            }else{
                Result result = new Result(410,"token无效",null);
                printJsonData(result,response);
            }
            // JWT jwt = JWTUtil.parseToken(token);

        }else{
            // 没有
            // a. 访问的是登录的路径的时候放行
            if(requestURI.equals("/usrlogin")){
                filterChain.doFilter(request,response);
            }else{
                // 返回json数据 没有登录
                Result result = new Result(400,"没有登录",null);
                printJsonData(result,response);
            }

        }


        // 有
            // a. 校验token
           // 正常
        // 获取 token中 username  资源的信息
        //









    }
    //

    public void printJsonData(Result result,HttpServletResponse response) throws IOException {
        // 以json的形式 传递除去
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(result);
        // 响应到前端
        response.setContentType("application/json;charset=utf8");
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
